<template>
	<u-popup :show="show" mode="bottom" @close="onClose" :round="10" safeAreaInsetBottom>
		<view class="filter-popup">
			<view class="filter-header">
				<text class="text">{{ title }}</text>
				<u-icon name="close" size="32rpx" color="#333" @click="onClose"></u-icon>
			</view>

			<scroll-view scroll-y class="filter-content">
				<template v-if="hasDataToDisplay">
					<view v-for="(section, sectionKey) in visibleSections" :key="sectionKey" class="filter-section">
						<text class="section-title" v-if="showTitle(section, filterType)">{{ section.title }}</text>
						<view class="section-tags">
							<view class="tag" :class="{ active: item.active }" 
								v-for="item in section.data" :key="item.id"
								@click="onSelectTag(sectionKey, item)" 
								v-if="section.data && section.data.length > 0"
							>
								<text class="text">{{ item.name.trim() }}</text>
							</view>
						</view>
					</view>
				</template>
				<view class="empty-placeholder" v-else>
					<text class="text">暂无筛选条件</text>
				</view>
			</scroll-view>

			<view class="filter-footer">
				<view class="btn reset" @click="onReset">重置</view>
				<view class="btn confirm" @click="onConfirm">确认</view>
			</view>
		</view>
	</u-popup>
</template>

<script>
	import { mapState } from 'vuex'

	export default {
		name: 'FilterPopup',

		props: {
			show: {
				type: Boolean,
				default: false
			},
			filterType: {
				type: String,
				default: 'more'
			},
			activeFilters: {
				type: Object,
				default: () => ({})
			}
		},

		data() {
			return {
				filterData: {
					parkingFee: [],
					chargingType: [],
					serviceType: [],
					parkingType: [],
					technologyFeatures: []
				}
			}
		},

		computed: {
			...mapState(['parkingFee', 'chargingType', 'serviceType', 'parkingType', 'technologyFeatures']),

			title() {
				const titles = {
					'parking': '停车费筛选',
					'charging': '充电方式筛选',
					'facility': '配套服务筛选',
					'more': '更多筛选'
				}
				return titles[this.filterType]
			},
			
			type() {
				const typeData = {
					'parking': 'parkingFee',
					'charging': 'chargingType',
					'facility': 'serviceType',
					'more': ''
				}
				return typeData[this.filterType]
			},
			
			isActive() {
				return (value) => {
					if (this.activeFilters && this.type != '' && this.activeFilters[this.type]) {
						return this.activeFilters[this.type].includes(parseInt(value))
					}
					return false
				}
			},

			sections() {
				return {
					parking: {
						title: '停车费',
						hideTitle: this.filterType !== 'more',
						data: this.filterData.parkingFee
					},
					charging: {
						title: '充电方式',
						hideTitle: this.filterType !== 'more',
						data: this.filterData.chargingType
					},
					facility: {
						title: '配套服务',
						hideTitle: this.filterType !== 'more',
						data: this.filterData.serviceType
					},
					parkingType: {
						title: '停车场',
						data: this.filterData.parkingType
					},
					technology: {
						title: '科技特色',
						data: this.filterData.technologyFeatures
					}
				}
			},

			visibleSections() {
				if (this.filterType === 'more') {
					return this.handleBatchFilterActive(this.sections);
				}
				
				// 确保过滤类型存在于sections中
				if (this.sections[this.filterType]) {
					return {
						[this.filterType]: this.handleFilterActive(this.sections[this.filterType])
					};
				}
				
				// 如果没有匹配的类型，返回空对象
				return {};
			},

			hasDataToDisplay() {
				return Object.values(this.visibleSections).some(section => 
					section.data && section.data.length > 0
				);
			}
		},

		watch: {
			show: {
				immediate: true,
				handler(val) {
					console.log(this.activeFilters)
					if (val) {
						this.initFilterData()
					}
				}
			}
		},

		mounted() {
			this.getLabelList()
			uni.$on('loginSuccessEvent', () => this.getLabelList());
		},

		methods: {
			handleFilterActive(data) {
				data.data.map(item => item.active = this.isActive(item.value))
				return data;
			},
			
			handleBatchFilterActive(data) {
				const filterMapping = {
					parking: 'parkingFee',
					charging: 'chargingType',
					facility: 'serviceType',
					parkingType: 'parkingType',
					technology: 'technologyFeatures'
				};

				Object.keys(data).forEach(sectionKey => {
					const activeFiltersKey = filterMapping[sectionKey];
					if (this.activeFilters[activeFiltersKey]?.length) {
						data[sectionKey].data?.forEach(item => {
							item.active = this.activeFilters[activeFiltersKey].includes(parseInt(item.value));
						});
					}
				});

				return data;
			},
			
			// 获取筛选数据
			async getLabelList() {
				const res = await this.$http_api.dictData()
				if (!res) {
					return
				}
				const filterTypes = ['parkingFee', 'chargingType', 'serviceType', 'parkingType', 'technologyFeatures']
				filterTypes.forEach(type => {
					if (res[type]) {
						this.$store.dispatch('updateFilterDataAction', {
							type,
							data: res[type]
						})
					} else {
						this.$store.dispatch('updateFilterDataAction', {
							type,
							data: []
						})
					}
				})
			},

			// 初始化筛选数据
			initFilterData() {
				const types = ['parkingFee', 'chargingType', 'serviceType', 'parkingType', 'technologyFeatures']
				types.forEach(type => {
					// 深拷贝数据
					this.filterData[type] = JSON.parse(JSON.stringify(this[type] || []))
					
					// 根据父组件传入的筛选条件设置选中状态
					if (this.activeFilters[type]) {
						this.filterData[type].forEach(item => {
							if (item && this.activeFilters[type].includes(item.value)) {
								item.active = true
							}
						})
					}
				})
			},

			showTitle(section, filterType) {
				if (!section) return
				return filterType === 'more' || !section.hideTitle
			},

			onSelectTag(sectionKey, item) {
				if (!item) return
				item.active = !item.active
			},

			onReset() {
				Object.keys(this.filterData).forEach(key => {
					if (Array.isArray(this.filterData[key])) {
						this.filterData[key].forEach(item => {
							if (item) {
								item.active = false
							}
						})
					}
				})
				// 重置后立即通知父组件
				this.$emit('confirm', {})
			},

			onConfirm() {
				const activeFilters = {}
				
				Object.entries(this.filterData).forEach(([key, items]) => {
					if (Array.isArray(items)) {
						const activeValues = items
							.filter(item => item && item.active)
							.map(item => parseInt(item.value))
						
						if (activeValues.length) {
							activeFilters[key] = activeValues
						}
					}
				})

				this.$emit('confirm', activeFilters)
				this.onClose()
			},

			onClose() {
				this.$emit('close')
			}
		}
	}
</script>

<style lang="scss" scoped>
	.filter-popup {
		width: 100vw;
		max-height: 80vh;
		background: #fff;
		display: flex;
		flex-direction: column;
		border-radius: 30rpx 30rpx 0 0;

		.filter-header {
			padding: 30rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			flex-shrink: 0;

			.text {
				font-family: "PINGFANG";
				font-size: 32rpx;
				font-weight: 400;
				color: #333;
				flex: 2;
				text-align: center;
			}
		}

		.filter-content {
			flex: 1;
			overflow-y: auto;
			padding: 20rpx 30rpx;
			width: calc(100% - 60rpx);
			-webkit-overflow-scrolling: touch;

			.filter-section {
				margin-bottom: 40rpx;

				&:last-child {
					margin-bottom: 0;
				}

				.section-title {
					font-size: 28rpx;
					font-weight: 600;
					color: #333;
					font-family: "PINGFANG";
					margin-bottom: 20rpx;
				}

				.section-tags {
					display: flex;
					flex-wrap: wrap;
					margin: 20rpx -10rpx 0;

					.tag {
						width: calc((100% - 60rpx) / 3);
						margin: 0 10rpx 20rpx;
						padding: 15rpx 20rpx;
						background: #ddd;
						border-radius: 21rpx;
						border: 1rpx solid #F6F6F6;
						display: flex;
						align-items: center;
						justify-content: center;
						box-sizing: border-box;

						.text {
							font-size: 24rpx;
							color: #333;
							font-family: "PINGFANG";
							white-space: nowrap;
							overflow: hidden;
							text-overflow: ellipsis;
							max-width: 100%;
						}

						&.active {
							background: #E5EFFF;
							border: 1rpx solid #1C6EFB;

							.text {
								color: #1C6EFB;
							}
						}
					}
				}
			}
				
			.empty-placeholder {
				width: 100%;
				height: 100rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				
				.text {
					font-size: 26rpx;
					color: #999;
					font-family: "PINGFANG";
				}
			}
		}

		.filter-footer {
			padding: 20rpx 30rpx;
			display: flex;
			gap: 20rpx;
			border-top: 1rpx solid #eee;
			flex-shrink: 0;

			.btn {
				flex: 1;
				height: 85rpx;
				border-radius: 43rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 28rpx;
				font-weight: 400;
				font-family: "PINGFANG";

				&.reset {
					background: #fff;
					color: #1C6EFB;
					border: 1rpx solid #1C6EFB;
				}

				&.confirm {
					background: #1C6EFB;
					color: #fff;
				}
			}
		}
	}
</style>